﻿using System.Runtime.InteropServices;

namespace WebAPI.Utils;

public class RuntimeHelper
{
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public string GetNetworkUsage()
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            //return GetWindowsNetworkUsage();
        }

        return RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? GetLinuxNetworkUsage() : "Un supported operating system.";
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    private string GetLinuxNetworkUsage()
    {
        try
        {
            if (!File.Exists("/proc/net/dev"))
                return "Unable to access network statistics(Linux only)";

            var lines = File.ReadAllLines("/proc/net/dev");

            var networkInterfaces = lines
                .Skip(2) //跳过前两行标题
                .Select(line => line.Trim())
                .Where(line => line.Contains(":"))
                .Select(ParseNetworkLine)
                .ToList();

            return string.Join("\n", networkInterfaces.Select(ni =>
                $"{ni.Interface}:{ni.ReceivedMB:F2}MB received,{ni.TransmittedMB:F2}MB sent"));
        }
        catch (Exception ex)
        {
            return $"Error retrieving network usage on Linux:{ex.Message}";
        }
    }

    private (string Interface, double ReceivedMB, double TransmittedMB) ParseNetworkLine(string line)
    {
        var parts = line.Split([' ', ':'], StringSplitOptions.RemoveEmptyEntries);
        var interfaceName = parts[0];

        var receivedBytes = long.Parse(parts[1]); //接收字节
        var transmittedBytes = long.Parse(parts[9]); //发送字节

        return (
            Interface: interfaceName,
            ReceivedMB: receivedBytes / (1024.0 * 1024.0), //转换为MB
            TransmittedMB: transmittedBytes / (1024.0 * 1024.0) //转换为MB
        );
    }
    
    // 获取磁盘使用情况（Windows）
    public static string GetDiskUsage()
    {
        if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return "N/A";
        var drive = DriveInfo.GetDrives().FirstOrDefault(d => d.IsReady);
        return drive != null ? $"{drive.TotalFreeSpace / (1024 * 1024 * 1024)} GB free of {drive.TotalSize / (1024 * 1024 * 1024)} GB" : "N/A";
    }
}